/*
 * ValidResource.cpp
 *
 *  Created on: 2013. 9. 4.
 *      Author: mega@gamevil.com
 */

#include "ValidResource.h"
#include "../engine.h"
#include <algorithm>
#include "../NUtil/Pool.h"

namespace ProjectZ { namespace NResource {

ValidResource::ValidResource()
{
}

ValidResource::~ValidResource()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
}

void
ValidResource::Clear()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
	clsFlyTree.clear();
}

bool ValidResource::LoadResource()
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_data_validate_check");

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	Clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		ValidResource::Flyweight * pFly = new ValidResource::Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> pFly->_LEVEL >> pFly->_ZEN >> pFly->_GOLD
				>> pFly->_STR >> pFly->_DEX >> pFly->_CON >> pFly->_INT
				>> pFly->_STAT_P >> pFly->_HP >> pFly->_SP >> pFly->_ATT
				>> pFly->_DEF >> pFly->_SKILL_P
				>> pFly->_AVOID_RATE >> pFly->_CRITICAL_RATE >> pFly->_CRITICAL_DAMAGE
				>> pFly->_DAMAGES;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_LEVEL] = pFly;
	}

	return true;
}

ValidResource::Flyweight * ValidResource::GetFly(int level)
{
	auto iter = clsFlyTree.find(level);

	if( iter == clsFlyTree.end() )
		return NULL;
	else
		return iter->second;
}

} /* NResource */ } /* ProjectZ */
